package com.kpmg.datalake.autopackage.controller;

import com.alibaba.fastjson.JSONObject;
import com.kpmg.datalake.autopackage.model.VersionManager;
import com.kpmg.datalake.autopackage.service.VersionManagementService;
import com.kpmg.datalake.autopackage.utils.ExcelOperateUtil;
import com.kpmg.datalake.autopackage.vo.VersionManagerDTO;
import com.kpmg.datalake.autopackage.vo.VersionManagerVO;
import com.kpmg.datalake.common.enums.ResultCodeEnum;
import com.kpmg.datalake.common.utils.ResponseUtils;
import com.kpmg.datalake.common.vo.ServerResponse;
import com.kpmg.datalake.db.model.SysUsr;
import com.kpmg.datalake.operatelog.annotation.OptLog;
import com.kpmg.datalake.operatelog.enums.LogTypeEnum;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.apache.commons.io.IOUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

/**
 * @Author: Richard.ji [richard.ji@kpmg.com]
 * @Date: 2018-07-13 10:13:40
 * @Description: 版本管理
 */
@RestController
@RequestMapping("/pkgauto")
public class VersionManagementController {
    private static final Logger LOG = LoggerFactory.getLogger(VersionManagementController.class);

    @Autowired
    private VersionManagementService versionManagementService;

    @Value("${template.path}")
    private String templatePath;

    /**
     * 获取版本信息
     * @return
     */
    @RequestMapping(value = "/getVersionInfo")
    @OptLog(logType = LogTypeEnum.OPERATION, module = "autoPackage", description = "查询VBA版本")
    public ServerResponse getVersionInfoList() {
        LOG.info("获取版本信息");

        try {
            ServerResponse severResponse = versionManagementService.getVersionInfoList();

            if(StringUtils.isEmpty(severResponse.getData())){
                return ServerResponse.createByErrorMessage("版本信息为空");
            }else{
                return severResponse;
            }
        } catch (Exception e){
            LOG.error("获取版本信息失败,异常{}", e);
            return ServerResponse.createByErrorMessage("获取版本信息失败");
        }
    }

    /**
     * 获取版本信息
     * @return
     */
    @PostMapping(value = "/getVersionInfoBySearch")
    @OptLog(logType = LogTypeEnum.OPERATION, module = "autoPackage", description = "查询VBA版本")
    public ServerResponse getVersionInfoBySearch(@RequestBody VersionManagerVO versionManagerVO) {
        LOG.info("获取版本信息");

        try {

            VersionManagerDTO versionManagerDTO = new VersionManagerDTO();
            versionManagerDTO.setFileName(versionManagerVO.getFileName());
            versionManagerDTO.setVersionInfo(versionManagerVO.getComments());
            versionManagerDTO.setPageIndex(versionManagerVO.getPageIndex());
            versionManagerDTO.setPageSize(versionManagerVO.getPageSize());

            return versionManagementService.getVersionInfoListBySearch(versionManagerDTO);

        } catch (Exception e){
            LOG.error("获取版本信息失败,异常{}", e);
            return ServerResponse.createByErrorMessage("获取版本信息失败");
        }
    }

    /**
     * 下载vba文件
     * @param versionManagerVO
     * @param request
     * @param response
     */
    @PostMapping(value = "/downloadVersionFront")
    @OptLog(logType = LogTypeEnum.OPERATION, module = "autoPackage", description = "下载VBA版本")
    public void requestResultDownloadFront(@RequestBody VersionManagerVO versionManagerVO,
                                                     HttpServletRequest request, HttpServletResponse response)
        throws IOException {

        String fileName = versionManagerVO.getFileName();
        String filePath = versionManagerVO.getFilePath();

        ResponseUtils.setZipDownloadResponseHeader(fileName+".xlam", request, response);

        try (FileInputStream inputStream = new FileInputStream(filePath)) {
            IOUtils.copy(inputStream, response.getOutputStream());
            response.flushBuffer();
        } catch (Exception e) {
            LOG.error("下载查询请求结果文件异常:" + e.getMessage(), e);
          try (OutputStream outputStream = response.getOutputStream()) {
            String outString = JSONObject.toJSONString(ServerResponse.createByErrorCodeMessage(
                ResultCodeEnum.CODE4041.getCode(), e.getLocalizedMessage()));
            outputStream.write(outString.getBytes());
          }
        }
    }


    /**
     * VBA文件下载
     * @param id
     * @param request
     * @param response
     */
    @GetMapping(value = "/downloadVersion")
    @OptLog(logType = LogTypeEnum.OPERATION, module = "autoPackage", description = "下载VBA版本")
    public void requestResultDownload(@RequestParam(value = "id")String id,HttpServletRequest request, HttpServletResponse response){

        VersionManager ver = (VersionManager)versionManagementService.getVersionInfoListById(id).getData();
        String fileName = ver.getFileName();
        String filePath = ver.getFilePath();

        ResponseUtils.setZipDownloadResponseHeader(fileName+".xlam", request, response);

        try (FileInputStream inputStream = new FileInputStream(filePath)) {
            IOUtils.copy(inputStream, response.getOutputStream());
            response.flushBuffer();
        } catch (Exception e) {
            LOG.error("下载查询请求结果文件异常:" + e.getMessage(), e);
        }
    }

    /**
     * 上传VBA版本
     * @param file
     * @param fileName
     * @param comments
     * @param session
     * @return
     */
    @PostMapping(value = "/uploadVersion")
    @OptLog(logType = LogTypeEnum.OPERATION, module = "autoPackage", description = "添加VBA版本")
    public ServerResponse uploadIndustryTemplate (MultipartFile file, String fileName, String comments, HttpSession session) {
        try {
        	SysUsr user = (SysUsr) session.getAttribute("user");

        	String uploadPath = System.getProperty(templatePath);
        	String absolutePath = ExcelOperateUtil.handleFileStream(file, uploadPath, user);
        	VersionManagerVO versionManagerVO = new VersionManagerVO();
        	versionManagerVO.setFileName(fileName);
        	versionManagerVO.setFilePath(absolutePath);
        	versionManagerVO.setComments(comments);
        	versionManagerVO.setUserId(user.getUsrId());

        	//将信息保存到vrsn_mgt这个表中
        	this.saveVersion(versionManagerVO);
            return ServerResponse.createBySuccess();
        } catch (Exception e) {
            LOG.error("上传VBA版本异常:" + e.getMessage(), e);

            return ServerResponse.createByError();
        }
    }

    @PostMapping(value = "/saveVersion")
    @OptLog(logType = LogTypeEnum.OPERATION, module = "autoPackage", description = "添加VBA版本")
    public ServerResponse saveVersion(@RequestBody VersionManagerVO versionManagerVO) {

        LOG.info("保存VBA版本信息");

        try {
            VersionManagerDTO versionManager = new VersionManagerDTO();
            versionManager.setFileName(versionManagerVO.getFileName());
            versionManager.setFilePath(versionManagerVO.getFilePath());
            versionManager.setVersionInfo(versionManagerVO.getComments());
            versionManager.setUserId(versionManagerVO.getUserId());

            return versionManagementService.insertVersion(versionManager);

        } catch (Exception e){
            LOG.error("保存VBA版本信息失败,异常{}", e);
            return ServerResponse.createByErrorMessage("保存VBA版本信息失败");
        }
    }
}
